#include "FreeRTOS.h"
#include "task.h"
#include "oled.h"

void setup()
{
    OLED_Init();
}

#define TASK_STACK_SIZE 100
#define TASK_PRIORITY 1

int delay_ticks = 0;

/* 任务函数例程 */
void TaskFunction(void *pvParameters)
{
    char *task = (char *)pvParameters;
    if (task[4] == '2')
    {
        vTaskDelay(500);
    }
    for( ;; )
    {
        taskENTER_CRITICAL();
        OLED_ShowString(1, 6, task);
        OLED_ShowNum(2, 7, delay_ticks, 5);
        taskEXIT_CRITICAL();
        vTaskDelay(1000);
        if (task[4] == '1')
        {
            delay_ticks += 1;
        }
    }
    /* 安全起见，如果程序由于异常执行到这，则删除当前任务 */
    vTaskDelete( NULL );
}


TaskHandle_t task1;
TaskHandle_t task2;

int main(void)
{
    setup();
    OLED_ShowString(1, 1, "Task:");
    OLED_ShowString(2, 1, "Delay:");
    BaseType_t ret = xTaskCreate(TaskFunction, "Task1", TASK_STACK_SIZE, "Task1", TASK_PRIORITY, &task1);
    if (ret != pdPASS)
    {
        OLED_ShowString(3, 1, "Task1 ERROR!");
        return -1;
    }
    OLED_ShowString(3, 1, "Task1 Created!");
    delay_ticks = 0;
    OLED_ShowNum(4, 1, delay_ticks, 10);
    OLED_ShowString(4, 1, "Creating Task2!");
    ret = xTaskCreate(TaskFunction, "Task2", TASK_STACK_SIZE, "Task2", TASK_PRIORITY, &task1);
    if (ret != pdPASS)
    {
        OLED_ShowString(4, 1, "Task2 ERROR!");
        return -1;
    }
    OLED_ShowString(4, 1, "Task2 Created!");
    vTaskStartScheduler(); 
    OLED_ShowString(4, 1, "Never show!");
    return 0;
}